package com.cci.kangdao.externalData.service.impl;

import com.alibaba.fastjson.JSON;
import com.cci.kangdao.azureAD.AzureADTool;
import com.cci.kangdao.cipFleet.service.CipFleetService;
import com.cci.kangdao.cipapi.CipServiceApi;
import com.cci.kangdao.cipapi.EsnBasicInfoEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.dto.BaseResponse;
import com.cci.kangdao.externalData.dto.request.*;
import com.cci.kangdao.externalData.dto.response.ExternalDataUserResponse;
import com.cci.kangdao.externalData.model.SynchroESNInfo;
import com.cci.kangdao.externalData.model.SynchroUserInfo;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.CustomerEngineRelTService;
import com.cci.kangdao.service.InviteUserService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.SyncEsnAndUserId;
import com.cci.kangdao.utilTool.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gexin.fastjson.JSONArray;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author sw
 */
@Service("externalDataSynchroService")
public class ExternalDataSynchroServiceImpl implements ExternalDataSynchroService {

    private Logger log = Logger.getLogger(this.getClass().getName());
    @Resource
    private UserTDao userTDao;
    @Resource
    private DictionariesTDao dictionariesTDao;
    @Resource
    private UserLabelMapper userLabelMapper;
    @Resource
    private LoginDao loginDao;
    @Resource
    private CipServiceApi cipServiceApi;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Resource
    private CustomerEngineRelDao customerEngineRelDao;
    @Resource
    private ServiceAgrementDao serviceAgrementDao;
    @Resource
    private EngineMsgDao engineMsgDao;
    @Resource
    private EngineMasterDataMapper engineMasterDataMapper;
    @Resource
    private CustomerEngineRelTService customerEngineRelService;
    @Resource
    private SyncEsnAndUserId syncEsnAndUserId;
    @Resource
    private CipFleetService cipFleetService;
    @Resource
    private UserChannelTMapper userChannelTMapper;
    @Resource
    private PropertiesUtils propertiesUtils;
    @Resource
    private RolesTDao rolesTDao;
    @Resource
    private LyhSftpUtils lyhSftpUtils;
    @Resource
    private InviteUserService inviteUserService;

    @Value("${webClientSecret}")
    private String webClientSecret;
    @Value("${tenant}")
    private String tenant;
    @Value("${innerTenant}")
    private String innerTenant;
    @Value("${webClient_id}")
    private String webClient_id;
    @Value("${userPhotoUrl}")
    private String userPhotoUrl;
    @Value("${lyh.url}")
    private String lyhUrl;
    @Value("${lyh.token}")
    private String lyhToken;

    public static final String SYNC_USER = "/system/sync/user";
    public static final String SYNC_ESN = "/system/sync/esn";
    private Pattern WWID_PATTERN = Pattern.compile("^([A-Za-z]{2})([0-9A-Za-z]{3})$");

    /**
     * 同步用户
     * @param userRequest
     */
    @Override
    public BaseResponse synchroUser(ExternalDataUserRequest userRequest, String source) {
        String serviceChannel = dictionariesTDao.getDIntByDTableNameAndDValue("serviceChannel",source);
        ExternalDataUserResponse returnResponse = new ExternalDataUserResponse();
        List<ExternalDataUserResponse.UserInfo> userList = new ArrayList<>();
        try {
            for (SynchroUserInfo userInfo : userRequest.getUserList()) {
                ExternalDataUserResponse.UserInfo userResponse = new ExternalDataUserResponse.UserInfo();
                userResponse.setPhone(userInfo.getPhone());
                userResponse.setExternalUserId(userInfo.getUserId());
                UserT userT = userTDao.getUserByPhone(userInfo.getPhone());
                if (null != userT) {
                    //校验其他渠道
                    List<UserChannelT> channelList = userChannelTMapper.getUserChannelListByUserId(userT.getId());
                    if(CollectionUtils.isNotEmpty(channelList)){
                        List<String> channelNoList = channelList.stream().map(UserChannelT::getServiceChannel).filter(a -> StringUtils.isNotBlank(a)).collect(Collectors.toList());
                        if(!channelNoList.contains(serviceChannel)) {
                            userResponse.setSynchroType(0);
                        }
                    }
                    //是否为终端用户
                    int i = userTDao.isEndUser(userT.getId());
                    if (i > 0 && userResponse.getSynchroType() == 1) {
                        userResponse.setEAppUserId(String.valueOf(userT.getId()));
                        //更新
                        UserT updateUserT = new UserT();
                        updateUserT.setId(userT.getId());
                        updateUserT.setContact(userInfo.getContact());
                        //updateUserT.setUserSource(5);
                        userTDao.updateUserMsgById(updateUserT);
                    } else {
                        userResponse.setSynchroType(0);
                    }
                } else {
                    //注册用户为终端用户
                    userT = new UserT();
                    userT.setPhone(userInfo.getPhone());
                    userT.setContact(userInfo.getContact());
                    userT.setUserSource(5);
                    Long userId = registerEndUser(userT);
                    if(null != userId){
                        userT.setId(userId);
                        userResponse.setEAppUserId(String.valueOf(userId));
                        if (CollectionUtils.isNotEmpty(userInfo.getLabels())) {
                            for (Integer userLabel : userInfo.getLabels()) {
                                UserLabel label = new UserLabel();
                                label.setLaberType(userLabel);
                                label.setUserId(userT.getId());
                                label.setFlag(0);
                                label.setCreator(userT.getId());
                                label.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                                label.setIsRead(1);
                                userLabelMapper.insert(label);
                            }
                        }
                    }
                }
                log.info("同步老友汇用户结果:" + userResponse);
                if(userT.getId() != 0){
                    if (userResponse.getSynchroType() == 0) {
                        userChannelTMapper.delete(userT.getId(),serviceChannel, LocalTimeUtil.getRealCurrentTime());
                    } else {
                        //修改手机号还原之前账号
                        Long oldUserId = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(userInfo.getUserId(), serviceChannel);
                        if(null != oldUserId && !oldUserId.equals(userT.getId())){
                            UserT oldUser = userTDao.selectById(oldUserId);
                            if(null != oldUser){
                                //同步删除原账号cip车辆
                                syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(oldUserId);
                                userChannelTMapper.delete(oldUserId, serviceChannel, LocalTimeUtil.getRealCurrentTime());
                                //同步重新添加cip车辆
                                syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(oldUserId);
                            }
                            UserChannelT userChannel = userChannelTMapper.getUserChannelByUserIdAndChannel(userT.getId(), serviceChannel);
                            if(null == userChannel) {
                                UserChannelT userChannelT = new UserChannelT();
                                userChannelT.setCreator(userT.getId());
                                userChannelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                                userChannelT.setUserId(userT.getId());
                                userChannelT.setServiceChannel(serviceChannel);
                                userChannelT.setExternalUserId(userResponse.getExternalUserId());
                                userChannelTMapper.insert(userChannelT);
                            } else {
                                userChannel.setExternalUserId(userResponse.getExternalUserId());
                                userChannel.setUpdator(userT.getId());
                                userChannel.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                                userChannelTMapper.update(userChannel);
                            }
                            if(null != oldUser){
                                //将之前用的绑车信息重新同步到新账号
                                List<Map<String, Object>> listMapByUserId = customerEngineRelDao.getListMapByUserId(oldUserId);
                                if (CollectionUtils.isNotEmpty(listMapByUserId)) {
                                    for (Map<String, Object> customerEngineRelT : listMapByUserId) {
                                        customerEngineRelT.put("ID", null);
                                        customerEngineRelT.put("ServiceChannel","1");
                                        customerEngineRelT.put("UserId", userT.getId());
                                        customerEngineRelT.put("Creator", userT.getId());
                                        customerEngineRelT.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                                        customerEngineRelT.put("Updator", userT.getId());
                                        customerEngineRelT.put("UpdateTime", LocalTimeUtil.getRealCurrentTime());
                                        customerEngineRelDao.newAddCustomerEngineRel(customerEngineRelT);
                                    }
                                }
                                //将新加的数据同步到cip
                                syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userT.getId());
                                //修改车队删除外部id
                                cipFleetService.updateFleetByUserId(oldUserId, userT.getId(),userInfo.getUserId(),Integer.valueOf(serviceChannel));
                                //修改vip用户
                                userTDao.updateVehicleByUserId(oldUserId,userT.getId());
                                userTDao.updateToSharedByUserId(oldUserId,userT.getId(),userT.getUserName(),userT.getPhone());
                                userTDao.updateSharedByUserId(oldUserId,userT.getId());
                            }
                        }

                        if(null == oldUserId){
                            //同步删除原账号cip车辆
                            syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(userT.getId());
                            UserChannelT userChannel = userChannelTMapper.getUserChannelByUserIdAndChannel(userT.getId(), serviceChannel);
                            if(null == userChannel) {
                                UserChannelT userChannelT = new UserChannelT();
                                userChannelT.setCreator(userT.getId());
                                userChannelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                                userChannelT.setUserId(userT.getId());
                                userChannelT.setServiceChannel(serviceChannel);
                                userChannelT.setExternalUserId(userInfo.getUserId());
                                userChannelTMapper.insert(userChannelT);
                            } else {
                                userChannel.setExternalUserId(userInfo.getUserId());
                                userChannel.setUpdator(userT.getId());
                                userChannel.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                                userChannelTMapper.update(userChannel);
                            }
                            //同步添加新账号cip车辆
                            syncEsnAndUserId.asSyncEsnAndUserIdAddByuserId(userT.getId());
                            //修改车队
                            cipFleetService.updateFleetListByUserId(userT.getId());
                        }
                        //上传esn文件同步老友汇
                        this.pushLyhEsnListByUserId(userT.getId());
                    }
                    userList.add(userResponse);
                }
            }
        } catch (Exception e) {
            log.error(e);
            return BaseResponse.error("未知错误");
        }
        returnResponse.setUserList(userList);
        return BaseResponse.success(returnResponse);
    }

    @Override
    public BaseResponse synchroEsn(Long userId, String externalUserId,List<SynchroESNInfo> esnRequestList, String serviceChannel) {
        try {
            if(CollectionUtils.isNotEmpty(esnRequestList)){
                log.info("同步老友会esn入参:" + esnRequestList);
                List<SynchroESNInfo> addEsnInfoList = new ArrayList<>();
                List<SynchroESNInfo> updateEsnInfoList = new ArrayList<>();
                List<SynchroESNInfo> deleteEsnInfoList = new ArrayList<>();
                List<SynchroESNInfo> collect = esnRequestList.stream()
                        .sorted(Comparator.comparing(SynchroESNInfo::getSysTime, Comparator.reverseOrder()))
                        .collect(Collectors.toList());
                ArrayList<SynchroESNInfo> esnInfoList = collect.stream()
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getEsn()))),
                                        ArrayList::new
                                )
                        );
                log.info("同步老友会esn入参排序去重结果:" + esnInfoList);
                List<String> esnList = esnInfoList.stream().map(SynchroESNInfo::getEsn).filter(a -> null != a).collect(Collectors.toList());
                List<CustomerEngineRelT> engineList = customerEngineRelDao.getEngineByUserIdAndESNList(userId,esnList);
                for(SynchroESNInfo esnInfo : esnInfoList){
                    esnInfo.setEAppUserId(userId);
                    esnInfo.setExternalUserId(externalUserId);
                    if(esnInfo.getOperation().equals("ADD") || esnInfo.getOperation().equals("UPDATE")){
                        CustomerEngineRelT customerEngineRel = null;
                        for(CustomerEngineRelT customerEngineRelT: engineList){
                            if(customerEngineRelT.getEsn().equals(esnInfo.getEsn())){
                                customerEngineRel = customerEngineRelT;
                            }
                        }
                        if(null != customerEngineRel){
                            esnInfo.setDrivingLicensePhotoUrl(customerEngineRel.getDrivingLicensePhotoUrl());
                            esnInfo.setServiceChannel(customerEngineRel.getServiceChannel());
                            esnInfo.setInviteCode(customerEngineRel.getInviteCode());
                            esnInfo.setSalesChannel(customerEngineRel.getSalesChannel());
                            esnInfo.setOperation("UPDATE");
                        } else {
                            esnInfo.setOperation("ADD");
                        }
                    }
                    if(esnInfo.getOperation().equals("ADD")){
                        addEsnInfoList.add(esnInfo);
                    } else if(esnInfo.getOperation().equals("UPDATE")){
                        updateEsnInfoList.add(esnInfo);
                    } else if(esnInfo.getOperation().equals("DEL")){
                        deleteEsnInfoList.add(esnInfo);
                    }
                }
                //添加
                List<Map<String, Object>> addlist = new ArrayList<>();
                List<Map<String, Object>> updatelist = new ArrayList<>();
                List<Map<String, Object>> deletelist = new ArrayList<>();
                List<CustomerEngineRelT> engineRelList = new ArrayList<>();
                //验证是否签署了主动服务协议
                ServiceAgreement serviceAggrementDetail = serviceAgrementDao.getServiceAggrementDetail(userId, 0);
                if (Objects.isNull(serviceAggrementDetail)) {
                    ServiceAgreement serviceAgreement = new ServiceAgreement();
                    serviceAgreement.setUserId(userId);
                    serviceAgreement.setSignTime(Date_Util.getOnlyDate());
                    serviceAgreement.setTerminateTime(Date_Util.addMonth(60));
                    serviceAgreement.setCreator(userId);
                    serviceAgreement.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    serviceAgreement.setType(0);
                    String coreManagerAgreement = dictionariesTDao.getListByDTableName("CoreManagerAgreement");
                    serviceAgreement.setVersion(Integer.valueOf(coreManagerAgreement));
                    serviceAgrementDao.signServiceAgreement(serviceAgreement);
                }
                if(CollectionUtils.isNotEmpty(addEsnInfoList)){
                    //百万圆桌绑车
                    inviteUserService.addBwyzBind(addEsnInfoList.get(0).getEsn(), userId);
                    Map<String, Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
                    Map<String,Map<String,Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
                    for(SynchroESNInfo esnInfo : addEsnInfoList){
                        String plateNumber = esnInfo.getPlateNumber();
                        String esn = esnInfo.getEsn();
                        //添加数据
                        CustomerEngineRelT customerEngineRelT = new CustomerEngineRelT();
                        customerEngineRelT.setPhone(esnInfo.getPhone());
                        customerEngineRelT.setEsn(esnInfo.getEsn());
                        customerEngineRelT.setPlateNumber(esnInfo.getPlateNumber());
                        customerEngineRelT.setDrivingLicensePhotoUrl(esnInfo.getDrivingLicensePhotoUrl());
                        customerEngineRelT.setEquipmentType(1);
                        customerEngineRelT.setUserId(userId);
                        customerEngineRelT.setServiceChannel(serviceChannel);
                        //esn主数据
                        EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
                        //调用cip接口获取esn信息
                        EsnBasicInfoEntity esnEntityInfo = null;
                        EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                        if(null != engineMasterData){
                            esnEntityInfo = new EsnBasicInfoEntity();
                            esnEntityInfo.setServiceModelName(engineMasterData.getServiceModelName());
                            esnEntityInfo.setEmissionLevel(engineMasterData.getRelBulletinTelAboEmissionLevel());
                            esnEntityInfo.setFuelType(engineMasterData.getEngineFuelType());
                            esnEntityInfo.setVin(engineMasterData.getBulletinTelVin());
                        }
                        Map<String, Object> engineMsgMap = new HashMap<>();
                        int fleetEmissionLevelDInt = -1;
                        int fleetFuelTypeDInt = -1;
                        //设置排放信息
                        String smn = "";
                        if(null != esnEntityInfo){
                            String emissionLevel =  esnEntityInfo.getEmissionLevel();
                            String fuelType = esnEntityInfo.getFuelType();
                            smn =  esnEntityInfo.getServiceModelName();
                            //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
                            if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)){
                                Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,emissionLevel);
                                if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                                    fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                                }
                            }
                            //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                            if(MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)){
                                Map<String,Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap,fuelType);
                                if(MapUtils.isNotEmpty(fleetFuelTypeDicMap)){
                                    fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap,"DInt",-1);
                                }
                            }
                            engineMsgMap.put("model",emissionLevel);
                        }
                        engineMsgMap.put("EsnApplicationType",fleetEmissionLevelDInt);
                        engineMsgMap.put("EsnPowerType",fleetFuelTypeDInt);
                        engineMsgMap.put("ESN", esn);
                        if(StringUtils.isNotEmpty(smn)){
                            engineMsgMap.put("SMN", smn);
                        }
                        engineMsgMap.put("equipmentNo", plateNumber);
                        if(null == engineMsg){
                            //保存发动机信息
                            engineMsgDao.newInsertEngineMsg(engineMsgMap);
                            //将新插入发动机信息ID放入关联表中
                            customerEngineRelT.setEngineMsgId(MapUtils.getLong(engineMsgMap, "id"));
                        }else{
                            engineMsgMap.put("id", engineMsg.getId());
                            if(null == esnEntityInfo){
                                engineMsgMap.put("model", engineMsg.getModel());
                            }
                            engineMsgDao.updateEngineMsg(engineMsgMap);
                            customerEngineRelT.setEngineMsgId(engineMsg.getId());
                        }
                        customerEngineRelT.setSmnName(smn);
                        customerEngineRelT.setCreator(userId);
                        customerEngineRelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                        int i = customerEngineRelDao.addVehicle(customerEngineRelT);
                        if(i > 0){
                            engineRelList.add(customerEngineRelT);
                            Map<String, Object> mapReport = new HashMap<>();
                            mapReport.put("ESN", esn);
                            mapReport.put("plateNumber", plateNumber);
                            mapReport.put("drivingLicense", StringUtils.isNotBlank(esnInfo.getDrivingLicensePhotoUrl()) ? 1 : 0);
                            mapReport.put("userId", esnInfo.getEAppUserId());
                            mapReport.put("originUserId",Integer.valueOf(esnInfo.getExternalUserId()));
                            mapReport.put("originChannel",Integer.valueOf(serviceChannel));
                            //来源
                            mapReport.put("deviceSource", syncEsnAndUserId.deviceSourceConvert(serviceChannel));
                            //渠道编号
                            mapReport.put("deviceChannel", "");
                            //渠道
                            mapReport.put("deviceOwner", "");
                            addlist.add(mapReport);
                        }
                    }
                }
                //修改
                for(SynchroESNInfo esnInfo : updateEsnInfoList){
                    //添加数据
                    CustomerEngineRelT customerEngineRelT = new CustomerEngineRelT();
                    customerEngineRelT.setEsn(esnInfo.getEsn());
                    customerEngineRelT.setVin(esnInfo.getPlateNumber());
                    customerEngineRelT.setDrivingLicensePhotoUrl(esnInfo.getDrivingLicensePhotoUrl());
                    customerEngineRelT.setUserId(esnInfo.getEAppUserId());
                    customerEngineRelT.setUpdator(esnInfo.getEAppUserId());
                    customerEngineRelT.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
                    customerEngineRelDao.updateSynchroCustomerEngineRel(customerEngineRelT);
                    Map<String, Object> mapReport = new HashMap<>();
                    mapReport.put("ESN", esnInfo.getEsn());
                    mapReport.put("plateNumber", esnInfo.getPlateNumber());
                    mapReport.put("drivingLicense", StringUtils.isNotBlank(esnInfo.getDrivingLicensePhotoUrl()) ? 1 : 0);
                    mapReport.put("userId", esnInfo.getEAppUserId());
                    mapReport.put("originUserId",Integer.valueOf(esnInfo.getExternalUserId()));
                    mapReport.put("originChannel",Integer.valueOf(serviceChannel));
                    //来源
                    mapReport.put("deviceSource", syncEsnAndUserId.deviceSourceConvert(esnInfo.getServiceChannel()));
                    //渠道编号
                    mapReport.put("deviceChannel", esnInfo.getInviteCode());
                    //渠道
                    mapReport.put("deviceOwner", esnInfo.getSalesChannel());

                    updatelist.add(mapReport);
                }
                //删除
                for(SynchroESNInfo esnInfo : deleteEsnInfoList){
                    //添加数据
                    CustomerEngineRelT customerEngineRelT = new CustomerEngineRelT();
                    customerEngineRelT.setEsn(esnInfo.getEsn());
                    customerEngineRelT.setUserId(esnInfo.getEAppUserId());
                    customerEngineRelT.setServiceChannel(serviceChannel);
                    customerEngineRelT.setDeleter(esnInfo.getEAppUserId());
                    customerEngineRelT.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
                    customerEngineRelDao.deleteSynchroCustomerEngineRel(customerEngineRelT);
                    Map<String, Object> mapReport = new HashMap<>();
                    mapReport.put("ESN", esnInfo.getEsn());
                    mapReport.put("plateNumber", esnInfo.getPlateNumber());
                    mapReport.put("drivingLicense", StringUtils.isNotBlank(esnInfo.getDrivingLicensePhotoUrl()) ? 1 : 0);
                    mapReport.put("userId", esnInfo.getEAppUserId());
                    mapReport.put("originUserId",Integer.valueOf(esnInfo.getExternalUserId()));
                    mapReport.put("originChannel",Integer.valueOf(serviceChannel));
                    deletelist.add(mapReport);
                }
                //同步cip车辆
                syncEsnAndUserId.asSyncEsnAndUserIdList(addlist, updatelist,deletelist,1);
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return BaseResponse.error("未知错误");
        }
        return BaseResponse.success();
    }

    /**
     * 同步老友会用户
     * @param userRequest
     */
    @Override
    public void synchroLyhUser(SynchroLyhUserRequest userRequest) {
        if(null != userRequest.getExternalUserId()){
            try{
                UserT user = userTDao.selectById(userRequest.getExternalUserId());
                UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userRequest.getExternalUserId(),"2");
                if(null != user && null != userChannelT){
                    userRequest.setPhone(user.getPhone());
                    String url = String.format(lyhUrl + SYNC_USER);
                    List<SynchroLyhUserRequest> list = new ArrayList<>();
                    list.add(userRequest);
                    String jsonString = JSONArray.toJSON(list).toString();
                    log.info("同步老友会用户；打印参数" + jsonString + "；url：" + url);
                    Header token = new BasicHeader("token", lyhToken);
                    String response = HttpUtils.postJson(url, jsonString, new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                            if (response.getStatusLine().getStatusCode() == 200
                                    || response.getStatusLine().getStatusCode() == 206) {
                                HttpEntity httpEntity = response.getEntity();
                                return EntityUtils.toString(httpEntity);
                            } else {
                                log.error("同步老友会用户失败；打印参数" + jsonString + "；返回结果：" + response);
                            }
                            return null;
                        }
                    },token);
                    if (StringUtils.isNotEmpty(response)) {
                        log.info("同步老友会用户成功；打印参数" + jsonString + "；返回结果：" + response);
                    }
                }
            } catch(Exception e){
                log.error("同步老友会用户失败；报错：" + e.getMessage(), e);
            }
        }
    }

    /**
     * 同步老友会esn
     * @param userId
     */
    @Override
    public void synchroLyhEsn(Long userId, String esn, String plateNumber, String operation) {
        if(null != userId && StringUtils.isNotBlank(esn)){
            UserT user = userTDao.selectById(userId);
            UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userId,"2");
            if(null != user && null != userChannelT){
                String url = String.format(lyhUrl + SYNC_ESN);
                Header token = new BasicHeader("token", lyhToken);
                SynchroLyhEsnRequest esnRequest = new SynchroLyhEsnRequest();
                esnRequest.setEsn(esn);
                esnRequest.setPlateNumber(plateNumber);
                esnRequest.setPhone(user.getPhone());
                esnRequest.setOperation(operation);
                try{
                    List<SynchroLyhEsnRequest> list = new ArrayList<>();
                    list.add(esnRequest);
                    String jsonString = JSONArray.toJSON(list).toString();
                    log.info("同步老友会esn；打印参数" + jsonString + "；url：" + url);
                    String response = HttpUtils.postJson(url, jsonString, new ResponseHandler<String>() {
                        @Override
                        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                            if (response.getStatusLine().getStatusCode() == 200
                                    || response.getStatusLine().getStatusCode() == 206) {
                                HttpEntity httpEntity = response.getEntity();
                                return EntityUtils.toString(httpEntity);
                            } else {
                                log.error("同步老友会esn失败；打印参数" + jsonString + "；返回结果：" + response);
                            }
                            return null;
                        }
                    },token);
                    if (StringUtils.isNotEmpty(response)) {
                        log.info("同步老友会esn成功；打印参数" + jsonString + "；返回结果：" + response);
                    }
                } catch(Exception e){
                    log.error("同步老友会esn失败；报错：" + e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 同步老友会esnList
     * @param userId
     */
    @Override
    public void synchroLyhEsnList(Long userId, String operation) {
        if(null != userId){
            UserT user = userTDao.selectById(userId);
            UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userId,"2");
            if(null != user && null != userChannelT){
                List<CustomerEngineRelT> listByUserId = customerEngineRelDao.getListByUserId(userId);
                if (CollectionUtils.isNotEmpty(listByUserId)) {
                    for(CustomerEngineRelT esnRequest : listByUserId){
                        synchroLyhEsn(userId, esnRequest.getEsn(), esnRequest.getVin(), operation);
                    }
                }
            }
        }
    }


    /**
     * 文件方式
     * 注册时接收老友会用户
     * @param userRequest
     */
    @Override
    public void receiveLyhUser(LyhFileUserRequest userRequest) {
        SFTPUtil sftp = null;
        try{
            if(StringUtils.isNotBlank(userRequest.getPhone())){
                Long userId = userRequest.getUserId();
                //是否为终端用户
                int i = userTDao.isEndUser(userId);
                List<UserChannelT> channelList = userChannelTMapper.getUserChannelListByUserId(userId);
                if(i > 0 && CollectionUtils.isEmpty(channelList)){
                    sftp = new SFTPUtil(lyhSftpUtils.sftpUserName, lyhSftpUtils.sftpPassword, lyhSftpUtils.sftpHost, lyhSftpUtils.sftpPort);
                    sftp.login();
                    String fileName = userRequest.getPhone() + ".json";
                    //查询老友汇是否有这个用户
                    boolean isFile = sftp.isFilePresent(lyhSftpUtils.sftpLyhUserPath, fileName);
                    log.info("注册时接收老友会用户；打印参数" + userRequest + "；isFile：" + isFile);
                    if(isFile){
                        byte[] byteArray = sftp.download(lyhSftpUtils.sftpLyhUserPath, fileName);
                        String json = new String(byteArray, StandardCharsets.UTF_8);
                        log.info("注册时接收老友会用户；文件内容：" + json);
                        ObjectMapper objectMapper = new ObjectMapper();
                        LyhFileUserRequest lyhFileUser = objectMapper.readValue(json, LyhFileUserRequest.class);
                        if(null != lyhFileUser && null != lyhFileUser.getUserId()){
                            ExternalDataUserRequest dataUserRequest =new ExternalDataUserRequest();
                            SynchroUserInfo userInfo = BeanUtils.convert(lyhFileUser,SynchroUserInfo.class);
                            List<SynchroUserInfo> userList = new ArrayList<>();
                            userList.add(userInfo);
                            dataUserRequest.setUserList(userList);
                            BaseResponse baseResponse = this.synchroUser(dataUserRequest,"laoyouhui");
                            if(null != baseResponse && baseResponse.getStatus() == 0){
                                //删除文件
                                sftp.delete(lyhSftpUtils.sftpLyhUserPath, fileName);
                            }
                        }
                    }
                }
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(null != sftp){
                sftp.logout();
            }
        }
    }

    /**
     * 文件方式
     * 推送老友会用户
     * @param userRequest
     */
    @Override
    public void pushLyhUser(LyhFileUserRequest userRequest) {
        SFTPUtil sftp = null;
        try{
            if(null != userRequest.getUserId()){
                UserT user = userTDao.selectById(userRequest.getUserId());
                UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userRequest.getUserId(),"2");
                if(null != user && null != userChannelT){
                    userRequest.setUserId(Long.valueOf(userChannelT.getExternalUserId()));
                    userRequest.setPhone(user.getPhone());
                    ObjectMapper objectMapper = new ObjectMapper();
                    String jsonString = objectMapper.writeValueAsString(userRequest);
                    log.info("推送老友会用户；文件内容：" + jsonString);
                    //上传用户文件
                    sftp = new SFTPUtil(lyhSftpUtils.sftpUserName, lyhSftpUtils.sftpPassword, lyhSftpUtils.sftpHost, lyhSftpUtils.sftpPort);
                    sftp.login();
                    String fileName = userRequest.getPhone() + ".json";
                    //查询老友汇是否有这个用户
                    boolean isFile = sftp.isFilePresent(lyhSftpUtils.sftpAppUserPath, fileName);
                    if(isFile){
                        //删除文件
                        sftp.delete(lyhSftpUtils.sftpAppUserPath, fileName);
                    }
                    InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
                    sftp.upload(lyhSftpUtils.sftpAppUserPath, fileName, inputStream);
                }
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(null != sftp){
                sftp.logout();
            }
        }
    }

    /**
     * 文件方式
     * 手动接收老友会车辆
     * @param userRequest
     */
    @Override
    public void receiveLyhVehicle(LyhFileUserRequest userRequest) {
        SFTPUtil sftp = null;
        try{
            if(null != userRequest.getUserId()){
                UserT user = userTDao.selectById(userRequest.getUserId());
                UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userRequest.getUserId(),"2");
                if(null != user && null != userChannelT){
                    sftp = new SFTPUtil(lyhSftpUtils.sftpUserName, lyhSftpUtils.sftpPassword, lyhSftpUtils.sftpHost, lyhSftpUtils.sftpPort);
                    sftp.login();
                    String fileName = user.getPhone() + ".json";
                    //查询老友汇是否有这个esn
                    boolean isFile = sftp.isFilePresent(lyhSftpUtils.sftpLyhVehiclePath, fileName);
                    log.info("接收老友会车辆；打印参数" + user.getPhone() + "；isFile：" + isFile);
                    if(isFile){
                        byte[] byteArray = sftp.download(lyhSftpUtils.sftpLyhVehiclePath, fileName);
                        String json = new String(byteArray, StandardCharsets.UTF_8);
                        log.info("接收老友会车辆；文件内容：" + json);
                        ObjectMapper objectMapper = new ObjectMapper();
                        List<SynchroLyhEsnRequest> esnList = objectMapper.readValue(json, new TypeReference<List<SynchroLyhEsnRequest>>(){});
                        if(CollectionUtils.isNotEmpty(esnList)){
                            List<SynchroESNInfo> esnInfoList = new ArrayList<>();
                            for(SynchroLyhEsnRequest esnInfo : esnList){
                                if(StringUtils.isNotBlank(esnInfo.getPhone())
                                        && StringUtils.isNotBlank(esnInfo.getEsn())
                                        && StringUtils.isNotBlank(esnInfo.getOperation())
                                        && StringUtils.isNotBlank(esnInfo.getSysTime())
                                        && (esnInfo.getOperation().equals("ADD") || esnInfo.getOperation().equals("UPDATE") || esnInfo.getOperation().equals("DEL"))){
                                    SynchroESNInfo esnSynchroInfo =BeanUtils.convert(esnList, SynchroESNInfo.class);
                                    esnSynchroInfo.setEAppUserId(user.getId());
                                    esnSynchroInfo.setExternalUserId(userChannelT.getExternalUserId());
                                    esnInfoList.add(esnSynchroInfo);
                                }
                            }
                            //同步车辆
                            BaseResponse baseResponse = this.synchroEsn(user.getId(),userChannelT.getExternalUserId(),esnInfoList, "2");
                            if(null != baseResponse && baseResponse.getStatus() == 0){
                                //删除文件
                                sftp.delete(lyhSftpUtils.sftpLyhVehiclePath, fileName);
                            }
                        }
                    }
                }
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(null != sftp){
                sftp.logout();
            }
        }
    }

    /**
     * 文件方式
     * 推送老友会esn
     * @param userId
     */
    @Override
    public void pushLyhEsn(Long userId, String esn, String plateNumber, String operation) {
        SFTPUtil sftp = null;
        try{
            if(null != userId && StringUtils.isNotBlank(esn)){
                UserT user = userTDao.selectById(userId);
                UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userId,"2");
                if(null != user && null != userChannelT){
                    SynchroLyhEsnRequest esnRequest = new SynchroLyhEsnRequest();
                    esnRequest.setEsn(esn);
                    esnRequest.setPlateNumber(plateNumber);
                    esnRequest.setPhone(user.getPhone());
                    esnRequest.setOperation(operation);
                    esnRequest.setSysTime(LocalTimeUtil.getRealCurrentTime());
                    List<SynchroLyhEsnRequest> list = new ArrayList<>();
                    list.add(esnRequest);
                    log.info("推送老友会esn；" + esnRequest);
                    //上传用户文件
                    sftp = new SFTPUtil(lyhSftpUtils.sftpUserName, lyhSftpUtils.sftpPassword, lyhSftpUtils.sftpHost, lyhSftpUtils.sftpPort);
                    sftp.login();
                    String fileName = user.getPhone() + ".json";
                    //查询app是否有这个文件
                    boolean isFile = sftp.isFilePresent(lyhSftpUtils.sftpAppVehiclePath, fileName);
                    if(isFile){
                        byte[] byteArray = sftp.download(lyhSftpUtils.sftpAppVehiclePath, fileName);
                        String json = new String(byteArray, StandardCharsets.UTF_8);
                        log.info("推送老友会esn历史文件；文件内容：" + json);
                        ObjectMapper objectMapper = new ObjectMapper();
                        List<SynchroLyhEsnRequest> esnList = objectMapper.readValue(json, new TypeReference<List<SynchroLyhEsnRequest>>(){});
                        if(CollectionUtils.isNotEmpty(esnList)){
                            list.addAll(esnList);
                        }
                        //删除文件
                        sftp.delete(lyhSftpUtils.sftpAppVehiclePath, fileName);
                    }
                    String jsonString = JSONArray.toJSON(list).toString();
                    log.info("推送老友会esn；文件内容：" + jsonString);
                    InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
                    sftp.upload(lyhSftpUtils.sftpAppVehiclePath, fileName, inputStream);
                }
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(null != sftp){
                sftp.logout();
            }
        }
    }

    /**
     * 文件方式
     * 添加标签后推送老友会esnList
     * @param userId
     */
    public void pushLyhEsnListByUserId(Long userId) {
        SFTPUtil sftp = null;
        try{
            if(null != userId){
                UserT user = userTDao.selectById(userId);
                List<SynchroLyhEsnRequest> esnList = customerEngineRelDao.getCustomerESNListByLyh(userId);
                if (CollectionUtils.isNotEmpty(esnList)) {
                    log.info("推送老友会userId:" +userId + ";esnList；" + esnList);
                    //上传用户文件
                    sftp = new SFTPUtil(lyhSftpUtils.sftpUserName, lyhSftpUtils.sftpPassword, lyhSftpUtils.sftpHost, lyhSftpUtils.sftpPort);
                    sftp.login();
                    String fileName = user.getPhone() + ".json";
                    //查询app是否有这个文件
                    boolean isFile = sftp.isFilePresent(lyhSftpUtils.sftpAppVehiclePath, fileName);
                    if(isFile){
                        byte[] byteArray = sftp.download(lyhSftpUtils.sftpAppVehiclePath, fileName);
                        String json = new String(byteArray, StandardCharsets.UTF_8);
                        log.info( "推送老友会esnList历史文件；文件内容：" + json);
                        ObjectMapper objectMapper = new ObjectMapper();
                        List<SynchroLyhEsnRequest> esnOldList = objectMapper.readValue(json, new TypeReference<List<SynchroLyhEsnRequest>>(){});
                        if(CollectionUtils.isNotEmpty(esnOldList)){
                            esnList.addAll(esnOldList);
                        }
                        //删除文件
                        sftp.delete(lyhSftpUtils.sftpAppVehiclePath, fileName);
                    }
                    String jsonString = JSONArray.toJSON(esnList).toString();
                    log.info("推送老友会esnList;userId:" + user.getId() + ";文件内容：" + jsonString);
                    InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
                    sftp.upload(lyhSftpUtils.sftpAppVehiclePath, fileName, inputStream);
                }
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(null != sftp){
                sftp.logout();
            }
        }
    }

    /**
     * 文件方式
     * 推送老友会esnList
     * @param userId
     */
    @Override
    public void pushLyhEsnList(Long userId, String operation) {
        SFTPUtil sftp = null;
        try{
            if(null != userId){
                UserT user = userTDao.selectById(userId);
                UserChannelT userChannelT = userChannelTMapper.getUserChannelByUserIdAndChannel(userId,"2");
                if(null != user && null != userChannelT){
                    List<CustomerEngineRelT> listByUserId = customerEngineRelDao.getListByUserId(userId);
                    if (CollectionUtils.isNotEmpty(listByUserId)) {
                        List<SynchroLyhEsnRequest> list = new ArrayList<>();
                        for(CustomerEngineRelT esnT : listByUserId){
                            SynchroLyhEsnRequest esnRequest = new SynchroLyhEsnRequest();
                            esnRequest.setEsn(esnT.getEsn());
                            esnRequest.setPlateNumber(esnT.getVin());
                            esnRequest.setPhone(user.getPhone());
                            esnRequest.setOperation(operation);
                            esnRequest.setSysTime(LocalTimeUtil.getRealCurrentTime());
                            list.add(esnRequest);
                        }
                        log.info("推送老友会userId:" + userId + ";esnList；" + list);
                        //上传用户文件
                        sftp = new SFTPUtil(lyhSftpUtils.sftpUserName, lyhSftpUtils.sftpPassword, lyhSftpUtils.sftpHost, lyhSftpUtils.sftpPort);
                        sftp.login();
                        String fileName = user.getPhone() + ".json";
                        //查询app是否有这个文件
                        boolean isFile = sftp.isFilePresent(lyhSftpUtils.sftpAppVehiclePath, fileName);
                        if(isFile){
                            byte[] byteArray = sftp.download(lyhSftpUtils.sftpAppVehiclePath, fileName);
                            String json = new String(byteArray, StandardCharsets.UTF_8);
                            log.info("推送老友会esnList历史文件；文件内容：" + json);
                            ObjectMapper objectMapper = new ObjectMapper();
                            List<SynchroLyhEsnRequest> esnList = objectMapper.readValue(json, new TypeReference<List<SynchroLyhEsnRequest>>(){});
                            if(CollectionUtils.isNotEmpty(esnList)){
                                list.addAll(esnList);
                            }
                            //删除文件
                            sftp.delete(lyhSftpUtils.sftpAppVehiclePath, fileName);
                        }
                        String jsonString = JSONArray.toJSON(list).toString();
                        log.info("推送老友会userId:" + userId + ";esnList；文件内容：" + jsonString);
                        InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
                        sftp.upload(lyhSftpUtils.sftpAppVehiclePath, fileName, inputStream);
                    }
                }
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        } finally {
            if(null != sftp){
                sftp.logout();
            }
        }
    }

    /**
     * 删除用户车辆车队信息
     * @param userId
     */
    @Override
    public void deleteEsnAndFleet(Long userId) {
        //同步删除cip车辆和车队
        syncEsnAndUserId.asSyncEsnAndUserIdDelByuserId(userId);
        customerEngineRelDao.deleteEngineRelByUserId(userId, LocalTimeUtil.getRealCurrentTime());
        cipFleetService.appDeleteFleetByUserId(userId);
        userChannelTMapper.deleteAll(userId,LocalTimeUtil.getRealCurrentTime());
    }


    /**
     * 注册用户角色为终端用户
     */
    @Override
    public Long registerEndUser(UserT userT){
        //获取token
        String token = AzureADTool.getManagementToken(tenant, webClient_id, webClientSecret);
        if (null == token) {
          return null;
        }
        //生成密码
        String pwd = NumberUtils.getStringRandom(8);
        Boolean isWWID = Boolean.FALSE;
        String userJson = null;
        // 符合wwid规则，判断是否是内部用户
        if(StringUtils.isNotBlank(userT.getUserName()) && WWID_PATTERN.matcher(userT.getUserName()).matches()){
            int isWwid = userTDao.isWWIDUser(userT.getUserName());
            if(isWwid <= 0){
                userJson = AzureADTool.getUser(userT.getUserName(), innerTenant, token);
                if(StringUtils.isNotEmpty(userJson)){
                    isWWID = Boolean.TRUE;
                }
            }
        }
        // 非wwid用户，先判断ad是否存在
        if(StringUtils.isEmpty(userJson)){
            userJson = AzureADTool.getUser(userT.getPhone(), tenant, token);
        }
        if (StringUtils.isEmpty(userJson)) {
            // 2、Azure AD使用token去新建用户
            userJson = AzureADTool.addUser(userT.getPhone(), pwd, tenant, token);
            if (StringUtils.isEmpty(userJson)) {
                return null;
            }
        }

        /**
         * 3、保存用户数据到数据库
         *  并给用户添加默认用户组、子用户组、角色
         */
        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(userJson);
            String adUserId = jsonObj.getString("id");
            //插入用户数据
            userT.setAduserId(adUserId);
            if (StringUtils.isBlank(userT.getUserName())) {
                userT.setUserName(userT.getPhone());
            }
            userT.setAzureToken("");
            if(isWWID){
                userT.setIsPwd(1);
                userT.setType(2);
                userT.setEmployeeNum(userT.getUserName());
            } else {
                userT.setIsPwd(0);
                userT.setType(1);
                userT.setEmployeeNum("");
            }
//            userT.setEmail("");
            userT.setPhotoUrl(userPhotoUrl);
            //获取用户组
            if(isWWID){
                userT.setUsergroupId(5);
                userT.setUsergroupSubId(0);
            } else {
                long userGroupID = Long.valueOf(propertiesUtils.getPropertiesValue("usergroupID"));
                long userGroupSubID = Long.valueOf(propertiesUtils.getPropertiesValue("usergroupSubID"));
                userT.setUsergroupId(userGroupID);
                userT.setUsergroupSubId(userGroupSubID);
            }
            log.error("参数："+ JSON.toJSONString(userT));
            int flag = loginDao.insertUserNew(userT);
            if (flag <= 0) {
                return null;
            }
            Long userId = userT.getId();
            Long userGroupId = userT.getUsergroupId();
            //修改用户来源字段
            int num = loginDao.updateUserSourceById(userT.getUserSource(), userT.getId());
            if(isWWID){
                // 获取WWID用户车联网
                List<Long> roles = rolesTDao.getUserGroupHasRolesIdList(userGroupId, "R0166");
                if (CollectionUtils.isNotEmpty(roles)) {
                    roles.forEach(roleId -> {
                        Map<String, Object> paramsMap = new HashMap();
                        paramsMap.put("userID", userId);
                        paramsMap.put("rolesID", roleId);
                        loginDao.insertUserRole(paramsMap);
                    });
                }
            } else {
                // 获取普通用户的权限
                List<Long> roles = rolesTDao.getUserGroupHasRolesIdList(userGroupId, "R0002");
                if (CollectionUtils.isNotEmpty(roles)) {
                    roles.forEach(roleId -> {
                        Map<String, Object> paramsMap = new HashMap();
                        paramsMap.put("userID", userId);
                        paramsMap.put("rolesID", roleId);
                        loginDao.insertUserRole(paramsMap);
                    });
                }
                //添加新手活动
                log.info("添加新手活动；userId:" + userT.getId());
                cipServiceApi.addNeophyteUser(userT.getId());
            }
        } catch (Exception e) {
            log.error("同步用户注册异常，注册用户：" + userT.getPhone() + e.getMessage(),e);
        }
        return userT.getId();
    }




}
